<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use Illuminate\Http\Request;


class WebController extends Controller
{
    public function __construct(){

        $global_cat = Cache::get('global_cat');
        if($global_cat===null){
            $global_cat = DB::table('cat')->get();
            Cache::set('global_cat', $global_cat ,100);
        }
          
        $global_cat_names = Cache::get('global_cat_names');
        if($global_cat_names===null){
            $global_cat_names = [];
            foreach($global_cat as $c){
            	$global_cat_names[$c->id] = $c;
            }
            Cache::set('global_cat_names', $global_cat_names ,100);
        }
        
        view()->share('global_cat', $global_cat);
        view()->share('global_cat_names', $global_cat_names);
        $this->online();
    }

    private function online(){
        $ip = request()->ip();
        $data = serialize([
            'ip'=>$ip,
            'time'=>time(),
        ]);
        #Hash实现
        Redis::hset('online',$ip,time());
        
        $all = Redis::hgetall('online');
        $person = [];
        $now  =time();
        foreach($all as $ip=>$time){
            if($now-$time>300){
                Redis::hdel('online',$ip);
            }else{
                $person[$ip] = $time;
            }
        }
        view()->share('online', $person);
        view()->share('online_size', Redis::hlen('online'));

        /*String实现
        Redis::sadd('online',$data);
        $all = Redis::smembers('online');
        $person = [];
        foreach($all as $p){
            $ps = unserialize($p);
            $person[$ps['ip']] = $ps['time'];
            $time  =time();
            if($time-$ps['time']>60){
                Redis::srem('online',$p);
            }
        }
        #dd($person,$all);
        view()->share('online', $person);
        */
    }
}